<?php
class Merchant_Service_OrderProccess
{
	protected $_order = null;	 
	protected $_orderCode = null;
	protected $_plan = null;
	protected $_customerId = null;
	protected $_procCnt  = null;
	protected $_products = null;
	protected $_chargeBalance = 0;//扣取费用
	protected $_isDispatch = false;//是否有分开（套餐/Balance）扣取
	protected $_chargeBalanceCurrency = null;
	protected $_outOfStock = false;
	protected $_outOfBalance = false;
	protected $_error = null;
	protected $_warning = null;
	protected $_shippingFeeError = false; 
	protected $_volume = null;
	protected $_weight = null;
	protected $_shipFee = 0.00;
	protected $_shipFeeCurrencyCode = 'RMB';
	protected $_status = null;
	protected $_checkOutOfPlan = false;
	protected $_customerPlan = null;
	protected $_feeEnforce = false;//强制扣款
	protected $_gwem = false;//注册在一个月内
	protected $_statuschange = false;//状态改变
	
	public function __construct($orderCode){	
		 if(isset($orderCode)){
			$this->_orderCode = $orderCode;
			$this->setOrder();
		}
		$this->setCustomer();
		$this->_plan = new Merchant_Service_Plan();
	}

	
	
	/**
	* 用户分发订单
	* @param orderCode
	* @return array|boolean success return boolean,false return array
	*/
	 public function submited($orderCode=null,$status,$isCheckPlan=false,$feeEnforce=false){

	 	if(isset($orderCode)){
			$this->_orderCode = $orderCode;
			$this->setOrder();
		}
		if($this->_order['process_status']>1){//订单处理中，不能修改
			 $this->_error = ' permissions deny, this order proccessing!';
			 return array('ask'=>'Error','orders_code'=>$this->_orderCode,'msg'=>$this->_error);
			
		}
		$this->_statuschange  = true;
	
		 
		$this->_feeEnforce = $feeEnforce;
		if($this->_order['customer_id']!=$this->_customerId){
			  $this->_error = 'no permissions to proccessing this order!';
			  return array('ask'=>'Error','orders_code'=>$this->_orderCode,'msg'=>$this->_error);
		}
		if($this->_order['orders_status'] == $status){				 
			return array('ask'=>'Success','orders_code'=>$this->_orderCode,'msg'=>'Success.');
		}
		
		
		$this->_status = $status;
         //init Transaction
         $customerBalance = new Merchant_Model_CustomerBalance();
         $dbAdapter = $customerBalance->getAdapter();
         $dbAdapter->beginTransaction();
         //事务  保证数据从主数据库取得
//		print_r($this->_order);exit;
		switch($status){
			case 0:
				
			case 1:
				
			case 2:
				$this->vaildateOrder();
				if(!empty($this->_error)){
					$dbAdapter->rollback();
					return array('ask'=>'Error','orders_code'=>$this->_orderCode,'msg'=>is_array($this->_error)?implode(",",$this->_error):$this->_error);		
				}
				//TODO
				if($this->_order['process_status']>1){
					$dbAdapter->rollback();
					return array('ask'=>'Error','orders_code'=>$this->_orderCode,'msg'=>"no permissions to proccessing this order.");	
				}
				if($this->_order['process_status']==1){//订单待下架，回退费用
					 //订单退回草稿状态，退回预扣的费用 退回总冻结的可用库存					
					try{
						//更新运输状态
						$row = array('os_status'=>'0');
						Merchant_Service_OrderShip::updateByOrdersCode($row, $this->_order['orders_code']);
						
						//订单退回草稿
						$row_order = array (
							"process_status" => 0,
							"process_status" => 0,
							"import_status"=>0,
							"print_time" => 0,
						);
						$this->changeStatus($row_order);
						
						//退回预扣费用
						$this->feeBack();
						//更新总冻结可用库存
						$this->productStocketBack();

					}catch(Exception $e){
						$dbAdapter->rollback();
						
						return array('ask'=>'Error','orders_code'=>$this->_orderCode,'msg'=>$e->getMessage());
					}
				}
				
				break;
			case 3:		
				try{
					
					$this->validateProduct();	
					if(!empty($this->_error)){
						$dbAdapter->rollback();
						return array('ask'=>'Error','orders_code'=>$this->_orderCode,'msg'=>is_array($this->_error)?implode(",",$this->_error):$this->_error);		
					}	
					$this->vaildateOrder();
					if(!empty($this->_error)){
						$dbAdapter->rollback();
						return array('ask'=>'Error','orders_code'=>$this->_orderCode,'msg'=>is_array($this->_error)?implode(",",$this->_error):$this->_error);		
					}	
					$this->picking();
									
					if($this->_outOfStock){
						$dbAdapter->rollback();
						$this->update();
						return array('ask'=>'Error','err_type'=>'stock','orders_code'=>$this->_orderCode,'msg'=>is_array($this->_error)?implode(",",$this->_error):$this->_error);		
					}	

					
					$this->shippingFee();
						
					if($this->_shippingFeeError==true){
						$dbAdapter->rollback();
						$this->update();
						return array('ask'=>'Error','orders_code'=>$this->_orderCode,'msg'=>is_array($this->_error)?implode(",",$this->_error):$this->_error);		
					}
					
					$this->holdShippingFee();
					if($this->_outOfBalance==true){
						$dbAdapter->rollback();	
						$this->update();
						return array('ask'=>'Error','err_type'=>'balance','orders_code'=>$this->_orderCode,'msg'=>is_array($this->_error)?implode(",",$this->_error):$this->_error);		
					}
				}catch(Exception $e){
					$dbAdapter->rollback();
					return array('ask'=>'Error','orders_code'=>$this->_orderCode,'msg'=>'Internal Error ! exception');		
				}
				break;
            default:
                $dbAdapter->rollback();
                return array('ask'=>'Error','orders_code'=>$this->_orderCode,'msg'=>'Internal Error.');
                break;
		}
		
		
		
		
		if(!$this->update()){
			$dbAdapter->rollback();	
			return array('ask'=>'Error','orders_code'=>$this->_orderCode,'msg'=>'Internal Error ! order can not update');		
		}
		$dbAdapter->commit();
		return array('ask'=>'Success','orders_code'=>$this->_orderCode,'msg'=>'Success');
	 }	 
	 
	 /**
	  * 截单
	  */
	 public function stop(){
		$this->setCustomer();
	 	if($this->_order['customer_id']!=$this->_customerId){
			$this->_error = 'no permissions to proccessing this order!';
			return array('ask'=>'Error','orders_code'=>$this->_orderCode,'msg'=>$this->_error);
		}
		
		if($this->_order['orders_status']==0 && $this->_order['process_status']==0){
			return array('ask'=>'Success','msg'=>'Order has been deleted.');
		}

		if($this->_order['orders_status'] >4 || $this->_order['process_status']==5){
			return array('ask'=>'Error','msg'=>'Order status Can not be modify.');
		}
		
		if(($this->_order['orders_status']==3 && $this->_order['process_status']==1) || $this->_order['process_status']==0 ){
			$result = $this->submited($this->_orderCode,0,0,0);
			if($result['ask']=='Error'){
				$result['ask']='Error';
				$result['msg']=$result['msg'];
				return $result;
			}
		}
		//已进行过截单
		if($this->_order['underreview_status']==3 && $this->_order['orders_status']!='0' ){
			return array('ask'=>'Warning','msg'=>'Order processed.');
		}
		
	 	$obj = new Merchant_Model_Orders();
		$row=array(
			'underreview_status'=>3,
			'order_stop_date'=>date("Y-m-d H:i:s")
		);
	 	if($obj->update($row,$this->_order['order_id'],"order_id")){
	 		$this->stoporderlog();
			if($this->_order['orders_status']==3 && $this->_order['process_status']>1){
				return array('ask'=>'Warning','msg'=>'Order processing.');//需要后台操作确认
			}else{
				return array('ask'=>'Success','orders_code'=>$this->_orderCode,'msg'=>'Success');
			}
	 	}else{
	 		return array('ask'=>'Error','orders_code'=>$this->_orderCode,'msg'=>'Internal Error 2! order can not update!');
	 	}
	 }
	 
	 /**
	  * 截单写入日志
	  */
	 
	public function stoporderlog(){
	 	$logRow = array(
	 			"orders_code" => $this->_orderCode,
	 			"osh_type" => "Revise",
	 			"osh_statu" => $this->_status,
	 			"osh_create_date" => date("Y-m-d H:i:s"),
	 			"osh_comments" => "stop order to be underreview_status eq 3 ",
	 			"osh_remark" => "stoporder",
	 			"user_id" => -1,
	 			"osh_ip" => $_SERVER['REMOTE_ADDR'],
	 	);
	 	
	 	$model = new Merchant_Model_OrderStatusHistory();
	 	$model->add($logRow);
	 }
	
	/*
	 * 更改订单状态
	 * 
	 */
	public function changeStatus($row) {
		$obj = new Merchant_Model_Orders();
		if(!$obj->update($row,$this->_order['order_id'],"order_id")){
			throw new Exception("Order status Can not be modify.");
			return;
		}
	}
	/*
	 * 退回预扣费用
	 * 
	 */
	public function feeBack() {

		$note = 'back shipping fee '.$this->_order['shipping_fee_estimate'].'. Order:'.$this->_order['orders_code'];
		$options = array('cbhClass'=>2,	//正常扣款
						 'refCode'=>$this->_order['orders_code'],
						 'appType'=>4,	//物流费用回退
						 'cbhType'=>'1',
						 'vale'=>$this->_order['shipping_fee_estimate'],
						 'currencyCode'=>"RMB",
						 'note'=>$note
						);
						
		if(! Merchant_Service_CustomerBalance::procBalance($this->_order['customer_id'],$options)){
			throw new Exception("Back failure.");
		}
		
		
				
	}

	/*
	 * 更新总冻结可用库存
	 * 
	 */
	public function productStocketBack() {
		//获取订单产品
		$condition = array("orders_code"=>$this->_order['orders_code']);
		$order_products = Merchant_Service_OrderProduct :: getByCondition($condition);
		
		$results = array();
		foreach ($order_products as $op) {
			$warehouseId = 1;
			$product_stocket = Merchant_Service_ProductStocket :: getByProductId($op['product_id'],$warehouseId);

			$row_product_stocket = array (
				"ps_quantity" => ($product_stocket['ps_quantity'] + $op['op_quantity']),
				"ps_quantity_hold" => ($product_stocket['ps_quantity_hold'] - $op['op_quantity']),			
			);
 			
			if(!Merchant_Service_ProductStocket :: update($row_product_stocket, $product_stocket['product_id'],$warehouseId)){
				throw new Exception("Update inventory failure.");
				break;
			}
		}

	}
	
	 /*
	 *
	 *获取客户LOGIN信息
	 *
	 */
	 public function setCustomer($customerId=null){
		if($this->_customerId==''&& !$this->_customerId){ 
			if(!$customerId){
				$sessionUser = new Zend_Session_Namespace("customer");
				$customer = $sessionUser->customer;
				$this->_customerId = $customer['customer_id'];
			}else{
				$this->_customerId = $customerId;
			}
		}
	 }
	/**
	*注册日期在一个月内
	*/
	 private function getByCustomerIdGwem(){
		$CustomerModel= new Merchant_Model_Customer();
		$cRow=$CustomerModel->getByGwemCustomerId($this->_customerId);
		if(!empty($cRow)){
			$this->_gwem=true;
		}
	 }	
	/*
	*判断是否扣物流费用
	*return true=>不扣费, false=>正常扣费
	*/
	 private function getCheckFee(){
		if($this->_order['shipping_method']=='SELFPICKUP'){
			return true;
		}
		return false;
	 }
	
	 /*
	 *
	 *下架处理
	 *
	 */	 
	 private function picking(){
		$itemCnt = 0;
		foreach ($this->_products as $val){
			$warehouseId = isset($val['warehouse_id'])&&empty($val['warehouse_id'])?$val['warehouse_id']:1;//仓库
			
			if(!Merchant_Service_ProductStocket::pickingProcdut($val['product_id'],$val['op_quantity'],$warehouseId,$this->_customerId,"orders_code:".$this->_orderCode)){
				$this->_outOfStock = true;
				$this->_error = $val['product_sku']. "  Available inventory shortage.";
				break;
			}
			$pdObj = new Merchant_Service_Product();
			$productRow = $pdObj->getProductInfo($val['product_id'],$this->_customerId);
			$this->_volume += $productRow['product_length']*$productRow['product_width']*$productRow['product_height'];
			$this->_weight += $productRow['product_weight'];
			$itemCnt += $val['op_quantity'];
			$this->_procCnt = $itemCnt;
		}
	 }

	 
	 //TODO validate Shipping Info//
	 private function vaildateOrder(){
		$this->_error = Merchant_Service_FactoryValidate::factoryMethod($this->_order); 
	 }
	 
	 /*
	 *
	 *Calc shipping fee
	 */
	 private function shippingFee(){
 
		try{			
			if(!$this->getCheckFee()){//运输方式为自提不扣物流费用						 
			
				$shipMethod = Default_Service_ShipType::getByValue($this->_order['shipping_method'],$field='st_code');
		 
				$options = array('warehouseId'=>1,
								'countryId'=>$this->_order['consignee_country_id'],	
								'stId'=>$shipMethod['st_id'],
								'weight'=>$this->_weight,
								'length'=>1,
								'width'=>1,
								'height'=>$this->_volume,
								'customerId'=>$this->_customerId
								);
				$shipFeeObj = new Default_Service_ShipFeeCalc($options);		
				
				$fee = $shipFeeObj->calcFeeByType();
				
				if(!is_array($fee)){
					$this->_shippingFeeError = true;
					$this->_error = "Can not calculate shipping price for this order! "; 
				}else{
					$this->_shipFee = $fee['inter_fee'];				
					$this->_shipFeeCurrencyCode =  $fee['currency_code'];//TODO 更改运费计算，返回加上货币种类 
				}
				
			}
		}catch(Exception $e){
			$this->_shippingFeeError = true;
			$this->_error = "Can not calculate shipping price for this order! ";
			
		}
				 
	 }
	 
	 
	 /*
	* hold fee
	*
	*/
	 private function holdShippingFee(){
		if(!$this->getCheckFee()){//运输方式为自提不扣物流费用
			 
			$note = 'Withdrawal shipping fee '.$this->_shipFee.'. Order:'.$this->_order['orders_code'];
			$options = array('cbhClass'=>1,	//正常扣款
								 'refCode'=>$this->_order['orders_code'],
								 'appType'=>3,	//物流费用
								 'cbhType'=>'-1',
								 'vale'=>$this->_shipFee,
								 'currencyCode'=>$this->_shipFeeCurrencyCode,
								 'note'=>$note
								);
			$ress = Merchant_Service_CustomerBalance::procBalance($this->_customerId,$options);
		
			if(!$ress){
				$this->_error  = 'Insufficient amount of available.';
				$this->_outOfBalance = true;				 
			}
			 
		}	
	 }
	 
	 /*
	 *Update orders
	 *
	 */
	 
	 private function update(){
		$Obj = new Merchant_Model_Orders();
		$updateRow = array("orders_status"=>$this->_status);
		if($this->_status=='3'){
			$updateRow['process_status'] = 1;
			$updateRow['underreview_status'] = 0;
			if($this->_shipFee)		$updateRow['shipping_fee_estimate'] = $this->_shipFee;
			$updateRow['submit_time'] = date('Y-m-d H:i:s');
		}
		if($this->_outOfStock){
			$updateRow = array(
				"orders_status"=>4,
				"underreview_status" => 1
			);			
			$updateRow['process_status'] = 0;
		}
		
		if($this->_outOfBalance){
			$updateRow = array(
				"orders_status"=>4,
				"underreview_status" => 2
			);
			$updateRow['process_status'] = 0;
		}
		if($this->_shippingFeeError){
			$updateRow = array(
				"orders_status"=>4,
				"underreview_status" => 3
			);
			$updateRow['process_status'] = 0;
		}	
		$this->createOrderLog($updateRow);
		if($Obj->update($updateRow,$this->_orderCode,"orders_code")){
//			$this->writeLog();
			return true;
		}
		return false;
	 }
	 
	 private function setOrder(){
		if(!isset($this->_order)||$this->_order['orders_code']!=$this->_orderCode ){
			//init Transaction
			$customerBalance = new Merchant_Model_CustomerBalance();
			$dbAdapter = $customerBalance->getAdapter();		 
			$dbAdapter->beginTransaction();
			$orderRow = Merchant_Service_Orders::getByValue($this->_orderCode,'orders_code');
			if(empty($orderRow)){
				$this->_error = "Can not find this order!";
			}else{
				$this->_order = $orderRow;					
				$condition['orders_code'] = $this->_orderCode;
				$this->_products = Merchant_Service_OrderProduct::getByCondition($condition);			
				$this->_order['order_product'] = $this->_products;	
			}
			$dbAdapter->commit();
		}
	 }
	 
	 private function validateProduct(){
	 	$service_product = new Merchant_Service_Product();
	 	foreach($this->_products as $v){//过滤非激活状态的产品
	 		$product = $service_product->getProductBySku($v['product_sku'],$this->_customerId);
			
			if($product['product_status']!=1){				
				$this->_error[]  = $v['product_sku']. ' not active.';
			}
		}
	 }
	 /*
	 *
	 *Return Order Info
	 */
	 public function getOrder(){
		 return $this->_order;
	 } 
	 
	 public  function createOrderLog($shouldUpdate){
	 	if(is_array($this->_error)){
	 		$err = implode("<br/>",$this->_error);	 		
	 	}elseif(is_string($this->_error)){
	 		$err = $this->_error;
	 	}else{
	 		$err = "";
	 	}
	 	$logRow = array(
	 			"orders_code" => $this->_orderCode,
	 			"osh_type" => "",
	 			"osh_statu" => -1,
	 			"osh_create_date" => date("Y-m-d H:i:s"),
	 			"osh_comments" => $err,
	 			"osh_remark" => "",
	 			"user_id" => -1,
	 			"osh_ip" => $_SERVER['REMOTE_ADDR'],
	 	);
	 	$order_status=array(
	 			0=>'Delete',
	 			1=>'Draft',
	 			2=>'Confirm',
	 			3=>'Abnormal',
	 			4=>'Processing',
	 			5=>'Shipped',
	 			6=>'Delivered'
	 	);
	 	 
	 	$formOrder=Merchant_Service_Orders::getByValue($this->_orderCode,'orders_code');
	 	if($this->_statuschange){
	 		$logRow['osh_type']='General';
			if(!$this->_error){
				$logRow['osh_comments']='order status has been changed form '.
						$order_status[$this->_order['orders_status']].' to '.
						$order_status[$shouldUpdate['orders_status']];
			}			
			$logRow['osh_statu']=$order_status[$shouldUpdate['orders_status']];
			
	 	}else{
	 		$logRow['osh_type']='Revise';
	 		foreach ($shouldUpdate as $k=>$val){
	 			if ($formOrder[$k]!=$val){
	 				$logRow['osh_comments'].='order '.$k.' has been changed form '.
	 						$formOrder[$k].' to '.$val."<br>";
	 			}
	 		}
	 	}
	 
 		$logRow["osh_statu"] = $formOrder['orders_status'];
	 	
	 	$model = new Merchant_Model_OrderStatusHistory();
	 	$model->add($logRow);
	 	 
	 }
	 
	 
	 public function writeLog(){
		$logRow = array(
			"orders_code" => $this->_orderCode,
			"osh_type" => "General",
			"osh_statu" => $this->_status,
			"osh_create_date" => date("Y-m-d H:i:s"),
			"osh_comments" => "",
			"osh_remark" => "",
			"user_id" => -1,
			"osh_ip" => $_SERVER['REMOTE_ADDR'],
		);
		if($this->_outOfStock){
			$logRow["osh_statu"] = 4;
			$logRow["osh_comments"] = "out of stock";
		}
		if($this->_outOfBalance){
			$logRow["osh_statu"] = 4;
			$logRow["osh_comments"] = "out of balance";
		}
		$model = new Merchant_Model_OrderStatusHistory();
		$model->add($logRow);
	 }
	 
	 public static function addOrder($order_info){
		$error = Merchant_Service_Orders::validator($order_info);
	
		if(!empty($error)){
			$return['ask'] =false;
            $return['list']['error'] =$error;
			return $return;
		}
//        print_r($order_info);exit;
		$return = self::edit($order_info);
		$return['list']['error'] = array($return['list']['message']);

		return $return;
	 }
	 
	 public static function batchValidator($orders){
	 	$serviceObj = new Merchant_Service_Product();
//	 	print_r($orders);
	 	foreach($orders as $k=>$v){		
			foreach($v['order_product'] as $i=>$val){				
			   $product = $serviceObj->getProductBySku($val['SKU']);				   			
			   if($product||$product['product_status']!=1){//产品SKU激活状态			   	
	            	$orders[$k]['order_product'][$i]['err'] ='SKU not exists or not active';			   	
			   }			   
			}
	 	}
	 	
	 	return $orders;
	 }
	 
	 
	 public static function batchAddOrder($orders){
		$serviceObj = new Merchant_Service_Product();
	 	$return = array();
	 	foreach($orders as $k=>$v){		 		
	 		$order_product = array();
	 		$product_count = count($v['order_product']);
	 		$exists_count = 0;
			foreach($v['order_product'] as $i=>$val){				
			   $product = $serviceObj->getProductBySku($val['SKU']);	
			   if($product&&$product['product_status']==1){//产品SKU激活状态
			   		$exists_count++;
				   	$order_product[] =array(
					   'product_id' => $product['product_id'],
					   'cn_description' => $val,
					   //'hs_code' => $hs_code[$i],
					   //'op_origin' => $op_origin[$i],
					   'op_quantity' => $val['Qty'],
					   'product_sku' => $product['product_sku'],
					   'op_unit_price' => $product['product_declared_value'],
					   'op_subtotal' => round($product['product_declared_value']*$val['Qty'],2),
					   'op_declared_value' => round($product['product_declared_value']*$val['Qty'],2),
					   'op_weight' => round($product['product_weight']*$val['Qty'],2)
				   );
	           		$return[$k]['product_err'][$i] ='';
			   }else{
	            	$return[$k]['product_err'][$i] ='SKU not exists or not active';			   	
			   }			   
			}//提交产品SKU数量与合法的SKU数量	 		
	 		if($exists_count!=$product_count){
	 			 $return[$k]['error'] ="some SKU not exists or not active";				
	 		}else{		 				 		
				$error = Merchant_Service_Orders::validator($v);
				if(!empty($error)){
		            $return[$k]['error'] =$error;				
				}else{
		            $return[$k]['error'] ='';		
					$return[$k]['data']= self::edit($v);				
				}
	 		}
	 	}
	 	return $return;
	 }


	 public static function edit($orderInfo){
        $retrun =array();
        $return['ask'] =false;
        $return['list']['message'] = "Failure";
        $orderInfo['shipping_method'] = strtoupper($orderInfo['shipping_method']);

        $order = array(
            'customer_id' => $orderInfo['customer_id'],
            'consignee_address1' => $orderInfo['consignee_address1'],
            'consignee_address2' => $orderInfo['consignee_address2'],
            'consignee_city' => $orderInfo['consignee_city'],
            'consignee_company' => $orderInfo['consignee_company'],
            'consignee_country_id' => $orderInfo['consignee_country_id'],
            'consignee_email' => $orderInfo['consignee_email'],
            'consignee_first_name' => $orderInfo['consignee_first_name'],
            'consignee_last_name' => $orderInfo['consignee_last_name'],
            'consignee_phone' => $orderInfo['consignee_phone'],
            'consignee_region' => $orderInfo['consignee_region'],
            'consignee_zip' => $orderInfo['consignee_zip'],
            'customer_order_code' => $orderInfo['customer_order_code'],
            'parcel_contents' => $orderInfo['parcel_contents'],
            'parcel_declared_value' => $orderInfo['parcel_declared_value'],
            'parcel_quantity' => $orderInfo['parcel_quantity'],
            'remark' => $orderInfo['remark'],
            'shipping_method' => $orderInfo['shipping_method'],
            'shipping_fee_estimate' => $orderInfo['shipping_fee_estimate'],
            'orders_print_type' => self::getPrintType($orderInfo['order_product'])
        );  
        
		if(floatval($orderInfo['shipping_fee_estimate'])<=0&& $orderInfo['shipping_method']!="SELFPICKUP"){
			$return['list']['message'] = $orderInfo['customer_order_code'].' shipping_fee_estimate error';	
			return $return;
		}
		
        if($orderInfo['order_id']>0)
        {        	
            $order_id = $orderInfo['order_id'];
            $order_code= Merchant_Service_Orders::getByValue($order_id,'order_id');
            if($order_code['process_status']>=1){//订单处理中，不能修改
            	 $return['ask'] =false;
				 $return['ordersCode'] = $order_code['orders_code'];
	             $return['list']['message'] = "Order Code:{$order_code['orders_code']}  no pemission edit, this order processing.";	
	             return $return;	
            }
            //添加日志
            $row = $orderInfo;
            unset($row['order_product']);
//            print_r($order_code);exit;
            $_s =  new Merchant_Service_OrderProccess($order_code['orders_code']);
			$_s->createOrderLog($row);	
			
            
            Merchant_Service_Orders::update($order,$order_id);
            $condition =array('orders_code'=>$order_code['orders_code']);
            $orderProductSelect= Merchant_Service_OrderProduct::getByCondition($condition,'op_id');
            $opIdArr =array();
            foreach($orderProductSelect as $row){
                $opIdArr[] = $row['op_id'];
            }
            foreach($orderInfo['order_product'] as $order_product){
                $orderProductInfo = array(
                   'orders_code' => $order_code['orders_code'],
                   'product_id' => $order_product['product_id'],
                   'cn_description' => empty($order_product['cn_description'])?"":$order_product['cn_description'],
                   //'hs_code' => $order_product['hs_code'],
                   //'op_origin' => $order_product['op_origin'],                		
                   'op_category' => $order_product['op_category'],
                   'op_quantity' => $order_product['op_quantity'],
                   'product_sku' => $order_product['product_sku'],
                   'op_description' => $order_product['op_description'],
                   'op_unit_price' => $order_product['op_unit_price'],
                   'op_subtotal' => $order_product['op_unit_price'],
                   'op_declared_value' => $order_product['op_declared_value'],
                   'op_weight' => $order_product['op_weight'],
                );
				if(isset($order_product['op_ref_tnx'])) $orderProductInfo['op_ref_tnx'] = $order_product['op_ref_tnx'];
				if(isset($order_product['op_ref_item_id'])) $orderProductInfo['op_ref_item_id'] = $order_product['op_ref_item_id'];
				if(isset($order_product['op_ref_paydate'])) $orderProductInfo['op_ref_paydate'] = $order_product['op_ref_paydate'];

                if(in_array($order_product['op_id'],$opIdArr)){
                    unset($opIdArr[$order_product['op_id']]);
                    Merchant_Service_OrderProduct::update($orderProductInfo,$order_product['op_id']);
                }else{
                    Merchant_Service_OrderProduct::add($orderProductInfo);
                }
                foreach($opIdArr as $op_id){
                    Merchant_Service_OrderProduct::delete($op_id);
                }
            }
            $return['ask'] =true;
			$return['ordersCode'] = $order_code['orders_code'];
            $return['list']['message'] = "Order Code:{$order_code['orders_code']}  Update Success.";		
        }else{
            $order_code = Merchant_Service_OrderId::getOrderId('W',$orderInfo['customer_id']);
			
            $order['orders_status'] = 1;
            $order['orders_code'] = $order_code;
            $order['add_time'] = date('Y-m-d H:i:s');
			$model = new Merchant_Model_Orders();
			$db = $model->getAdapter();
			$db->beginTransaction();
			try{
				if(!Merchant_Service_Orders::add($order)){
						$db->rollback();
						$return['list']['message'] = 'Internal Error!  order can not add!';	
				}
				if(isset($orderInfo['regAccount']) && $orderInfo['regAccount']){
					$referInfo = $orderInfo['regAccount'];
					$referInfo['orders_code'] = $order_code;
					$referInfo['ori_create_time'] = $order['add_time'];
					$refObj = new Merchant_Model_OrderReferInfo();
					if(!$refObj->add($referInfo)){
						$db->rollback();
						$return['list']['message'] = 'Internal Error ! order refer info can not add';	
					}
				}
				
				foreach($orderInfo['order_product'] as $order_product){
					$orderProductInfo = array(
					   'orders_code' => $order_code,
					   'product_id' => $order_product['product_id'],
					   'cn_description' => empty($order_product['cn_description'])?"":$order_product['cn_description'],
					   //'hs_code' => $order_product['hs_code'],
					   //'op_origin' => $order_product['op_origin'],
					   'op_category' => $order_product['op_category'],
					   'op_quantity' => $order_product['op_quantity'],
					   'product_sku' => $order_product['product_sku'],
					   'op_description' => $order_product['op_description'],
					   'op_unit_price' => $order_product['op_unit_price'],
					   'op_subtotal' => $order_product['op_unit_price'],
					   'op_declared_value' => $order_product['op_declared_value'],
					   'op_weight' => $order_product['op_weight'],
					);
					if(isset($order_product['op_ref_tnx']) && $order_product['op_ref_tnx']) $orderProductInfo['op_ref_tnx'] = $order_product['op_ref_tnx'];
					if(isset($order_product['op_ref_item_id']) &&$order_product['op_ref_item_id'] ) $orderProductInfo['op_ref_item_id'] = $order_product['op_ref_item_id'];
					if(isset($order_product['op_ref_paydate']) && $order_product['op_ref_paydate']) $orderProductInfo['op_ref_paydate'] = $order_product['op_ref_paydate'];					

					if(!Merchant_Service_OrderProduct::add($orderProductInfo)){
						$db->rollback();
						$return['list']['message'] = 'Internal Error ! order product can not add';	
					}
				}
				$db->commit();
				$return['ask'] =true;
				$return['ordersCode'] = $order_code;
				$return['list']['message'] = "Order Code:{$order_code} Add Success.";
			}catch(Exception $e){
				$db->rollback();
				$return['list']['message'] = 'Internal Error ! exception 1'.$e->getMessage();	
			}
			 
           
        }
        return $return;
    }
	//检查打印类型
	public static function getPrintType($oProduct){
		$i = 0;
		$j = 0;
		foreach($oProduct  as $product){
			$j += $product['op_quantity'];
			$i++;
		}
		if($i==1 && $j==1) return 0;
		if($i==1 && $j>1) return 1;
		if($i>1 && $j>1) return 2;
		return -1;
	}
	
	/**
	 * 	获取订单的 shipping_fee_estimate 的值
	 *  $weight 为订单的所有产品重量；$product_skus为 产品product_sku 的一维数组
	 *  $warehouse_id 仓库ID；$country_id 国家ID；$shipping_method 物流方式
	 */
	
	public static function getEstimateFee($warehouse_id,$country_id,$shipping_method,$weight,$product_skus){
		$estimateFee = 0;
		$error = array();
		$model_product = new Merchant_Model_Product();
					
        $serviceObj = Merchant_Service_Product::getInstance();       
        $loginInfo = $serviceObj->getLoginInfo();
        $customerId = $loginInfo->customer["customer_id"];

		$products = $model_product->getProductBySkus($product_skus,$customerId);
		
		$extra_weight = 0;
		if($products){	//所有产品中产品包材重量最重
			$product_ids = array();
			foreach($products as $v){
				$product_ids[] = $v['product_id'];
			}
			$extra_weight = $model_product->getProductPackageWeightByProductId($product_ids);			
		}
			
        $shipType = Default_Service_ShipType::getByValue($shipping_method,'st_code');
        $array = array(
            'warehouseId'=>$warehouse_id,
            'countryId'=>$country_id,
            'stId'=> @$shipType['st_id'],
            'weight'=> ($weight+$extra_weight),
            'length'=> 0,
            'width'=> 0,
            'height'=> 0,
            'customerId'=>$customerId,
        );
        $obj =new Default_Service_ShipFeeCalc($array);
        $fee = $obj->calcFeeByType();
        
        if(is_array($fee)){
			$currency = Default_Service_Currency::changeCurrency("0.25","USD","RMB");	
        	if($currency){
        		$estimateFee = $fee['inter_fee']+$currency['value'];//加上包材费用
        	}
        }else{
        	$error = array(1);        	
        }
        if($estimateFee){
        	return $estimateFee;
        }
		return $error;
	}
	
}